﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Text;
using System.Data.SqlClient;
using System.Data;
using Microsoft.Practices.EnterpriseLibrary.Data;
using Microsoft.Practices.EnterpriseLibrary.Data.Sql;
using System.Data.Common;
using Dazaza.Framework.Entity;

namespace Dazaza.Framework.Data
{
    public class DataCommand
    {
        /// <summary>
        /// 只读
        /// </summary>
        public static Database CurrentDatabase_ReadOnly
        {
            get
            {
                return DataConnection.GetConnection("WebRead");
            }
        }

        /// <summary>
        /// 主库
        /// </summary>
        public static Database CurrentDatabase_Main
        {
            get
            {
                return DataConnection.GetConnection("Main");
            }
        }


        public DbCommand DbCommand
        {
            get;
            private set;
        }

        private Database CurrentDatabase
        {
            get;
            set;
        }

        private DbConnection _dbConn;
        public DbTransaction Transaction { get; private set; }

        public void BeginTran()
        {
            DbConnClose();
            _dbConn = CurrentDatabase.CreateConnection();
            _dbConn.Open();
            Transaction = _dbConn.BeginTransaction();
            DbCommand.Transaction = Transaction;
            //DbCommand.Connection = _dbConn;
        }
        public void CommitTran()
        {
            if (_dbConn != null && Transaction != null)
            {
                if (_dbConn.State != ConnectionState.Closed)
                {
                    Transaction.Commit();
                }
            }
        }

        public void RollbackTran()
        {
            if (_dbConn != null && Transaction != null)
            {
                if (_dbConn.State != ConnectionState.Closed)
                {
                    Transaction.Rollback();
                }
            }
        }
        public void DbConnClose()
        {
            if (_dbConn != null)
            {
                if (_dbConn.State != ConnectionState.Closed)
                    _dbConn.Close();
            }
        }

        public DataCommand(string commandText, CommandType commandType, string connectionStringKey)
        {
            CurrentDatabase = DataConnection.GetConnection(connectionStringKey);
            this.DbCommand = null;
            SetCommand(commandText, commandType);
        }
        /// <summary>
        /// 默认构造器
        /// </summary>
        /// <param name="commandText"></param>
        /// <param name="commandType"></param>
        public DataCommand(string commandText, CommandType commandType)
            : this(commandText, commandType, DataBaseType.Main)
        {

        }
        public DataCommand(DataBaseType dataBaseType)
        {
            SetCurrentDatabase(dataBaseType);
            this.DbCommand = null;
            SetCommand("select getdate()", CommandType.Text);
        }

        /// <summary>
        /// 重载
        /// </summary>
        /// <param name="commandText"></param>
        /// <param name="commandType"></param>
        /// <param name="dataBaseType"></param>
        public DataCommand(string commandText, CommandType commandType, DataBaseType dataBaseType)
        {
            SetCurrentDatabase(dataBaseType);
            this.DbCommand = null;
            SetCommand(commandText, commandType);
        }

        private void SetCurrentDatabase(DataBaseType dataBaseType)
        {
            switch (dataBaseType)
            {
                case DataBaseType.Main:
                    CurrentDatabase = CurrentDatabase_Main;
                    break;
                case DataBaseType.ReadOnly:
                    CurrentDatabase = CurrentDatabase_ReadOnly;
                    break;
            }
        }
        private void SetCommand(string commandText, CommandType commandType)
        {
            if (commandType == CommandType.StoredProcedure)
            {
                this.DbCommand = CurrentDatabase.GetStoredProcCommand(commandText);
            }
            else
            {
                this.DbCommand = CurrentDatabase.GetSqlStringCommand(commandText);
            }
        }
        #region parameters
        public Object GetParameterValue(string paramName)
        {
            return CurrentDatabase.GetParameterValue(DbCommand, paramName);
        }

        public void SetParameterValue(string paramName, SqlDbType dbType, Object val)
        {
            SqlParameter parameter = new SqlParameter(paramName, dbType);
            parameter.Value = val;
            this.DbCommand.Parameters.Add(parameter);
        }

        public void SetParameterValue(SqlParameter parameter)
        {
            DbCommand.Parameters.Add(parameter);
        }
        public void SetParameterValue(SqlParameter[] parameters)
        {
            if (parameters.Length > 0)
            {
                foreach (SqlParameter parameter in parameters)
                {
                    DbCommand.Parameters.Add(parameter);
                }
            }
        }
        #endregion

        public T ExecuteScalar<T>()
        {
            try
            {
                object scalar = Transaction == null ? CurrentDatabase.ExecuteScalar(DbCommand) : CurrentDatabase.ExecuteScalar(DbCommand, Transaction);
                if (scalar != null)
                {
                    return (T)scalar;
                }
                return default(T);
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine(ex.ToString());
                throw;
            }
        }

        public int ExecuteNonQuery()
        {
            try
            {
                if (Transaction == null)
                    return CurrentDatabase.ExecuteNonQuery(DbCommand);
                return CurrentDatabase.ExecuteNonQuery(DbCommand, Transaction);
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine(ex.ToString());
                throw;
            }
        }

        private IDataReader DoExecuteDataReader()
        {
            try
            {
                return CurrentDatabase.ExecuteReader(DbCommand);
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine(ex.ToString());
                throw;
            }
        }

        public T ExecuteEntity<T>() where T : class, new()
        {

            DataSet ds = null;
            DataTable dt = null;
            T entity = default(T);
            try
            {
                if (Transaction == null)
                {
                    ds = CurrentDatabase.ExecuteDataSet(DbCommand);

                }
                else
                {
                    ds = CurrentDatabase.ExecuteDataSet(DbCommand, Transaction);
                }
                if (ds != null && ds.Tables.Count > 0)
                {
                    dt = ds.Tables[0];
                    if (dt.Rows.Count > 0)
                    {
                        entity = EntityBuilder.BuildEntity<T>(dt.Rows[0]);
                    }

                }
                return entity;
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine(ex.ToString());
                throw;
            }
        }
        public List<T> ExecuteList<T>()
        {
            DataSet ds = null;
            DataTable dt = null;
            try
            {
                List<T> list = new List<T>();
                if (Transaction == null)
                {
                    ds = CurrentDatabase.ExecuteDataSet(DbCommand);
                }
                else
                {
                    ds = CurrentDatabase.ExecuteDataSet(DbCommand, Transaction);
                }
                if (ds != null && ds.Tables.Count > 0)
                {
                    dt = ds.Tables[0];
                    foreach (DataRow dr in dt.Rows)
                    {
                        T entity = dr.Field<T>(0);
                        list.Add(entity);
                    }

                }
                return list;
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine(ex.ToString());
                throw;

            }
            finally
            {

            }
        }
        public List<T> ExecuteEntityList<T>() where T : class, new()
        {
            DataSet ds = null;
            DataTable dt = null;
            try
            {
                List<T> list = new List<T>();
                if (Transaction == null)
                {
                    ds = CurrentDatabase.ExecuteDataSet(DbCommand);
                }
                else
                {
                    ds = CurrentDatabase.ExecuteDataSet(DbCommand, Transaction);
                }
                if (ds != null && ds.Tables.Count > 0)
                {
                    dt = ds.Tables[0];
                    foreach (DataRow dr in dt.Rows)
                    {
                        T entity = EntityBuilder.BuildEntity<T>(dr);
                        list.Add(entity);
                    }

                }
                return list;
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine(ex.ToString());
                throw;

            }
            finally
            {
                
            }
        }
    }

    public enum DataBaseType
    {
        //主库
        Main = 0,
        //只读
        ReadOnly = 1,
    }
}
